<template>
  <div class="user-select">
    <div class="select-reference" @click="openDialog">
      <div class="select-content">
        <span v-if="selectedUsers.length === 0" class="placeholder">{{ placeholder }}</span>
        <span v-else class="selected-text">{{ formatSelectedText }}</span>
      </div>
      <el-icon class="arrow-icon">
        <ArrowDown />
      </el-icon>
    </div>

    <el-dialog
      v-model="dialogVisible"
      title="选择人员"
      width="90%"
      class="user-select-dialog"
      append-to-body
      :before-close="handleDialogClose"
    >
      <div class="user-select-content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb" v-if="breadcrumb.length > 0">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item 
              v-for="(item, index) in breadcrumb" 
              :key="item.id"
              @click="navigateToLevel(index)"
            >
              {{ item.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索人员"
            clearable
            prefix-icon="Search"
            size="small"
          />
        </div>

        <!-- 已选列表 -->
        <div class="selected-list" v-if="selectedUsers.length > 0">
          <div class="selected-title">
            已选择 ({{ selectedUsers.length }})
            <el-button 
              type="primary" 
              link 
              @click="clearAllSelected" 
              class="clear-all-btn"
            >
              清空
            </el-button>
          </div>
          <div class="selected-items">
            <el-tag
              v-for="(user, index) in selectedUsers"
              :key="user.id"
              closable
              @close="removeSelected(user, index)"
              class="selected-item-tag"
            >
              {{ user.name }}
            </el-tag>
          </div>
        </div>

        <!-- 部门列表 -->
        <div class="department-list" v-if="currentLevel === 0 && departments.length > 0" v-loading="loading">
          <!-- 全选按钮，仅在无限制模式下显示 -->
          <div class="select-all" v-if="limit === 0">
            <el-checkbox 
              :model-value="isAllSelected"
              @change="handleSelectAllChange"
            >
              全部选择
            </el-checkbox>
          </div>

          <div 
            v-for="dept in departments" 
            :key="dept.id" 
            class="department-item"
            @click="goToSubDepartment(dept)"
          >
            <div class="item-content">
              <el-icon class="dept-icon"><Folder /></el-icon>
              <div class="dept-info">
                <div class="dept-name">{{ dept.name }}</div>
                <div class="dept-count" v-if="dept.userCount">({{ dept.userCount }}人)</div>
              </div>
            </div>
            
            <div class="item-action">
              <el-button 
                link 
                type="primary" 
                class="sub-dept-btn"
              >
                下级
              </el-button>
            </div>
          </div>
        </div>

        <!-- 用户列表 -->
        <div class="user-list" v-else v-loading="loading">  
          
          <div 
            v-for="user in filteredUsers" 
            :key="user.id" 
            class="user-item"
            @click="handleUserSelect(user)"
          >
            <el-avatar :size="36" :src="user.avatar" class="user-avatar">{{ user.name.charAt(0) }}</el-avatar>
            <div class="user-info">
              <div class="user-name">{{ user.name }}</div>
              <!-- <div class="user-department">{{ user.department }}</div> -->
            </div>
            
            <div class="user-action">
              <el-checkbox 
                :model-value="isSelected(user)"
                :disabled="isCheckboxDisabled(user)"
                @click.stop
                @change="(val) => handleCheckboxChange(val, user)"
              />
            </div>
          </div>
          
          <div v-if="filteredUsers.length === 0 && !loading && currentLevel > 0" class="no-data">
            暂无数据
          </div>
        </div>

        <div class="pagination-box" v-if="showPagination && currentLevel > 0">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>

        <!-- 限制提示 -->
        <div class="limit-tip" v-if="limit > 0 && selectedUsers.length >= limit">
          最多只能选择 {{ limit }} 个用户
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button-group>            
            <el-button @click="goToParentLevel" v-if="currentLevel > 0" title="返回上一级">返回</el-button>
            <el-button @click="goToTopLevel" v-if="currentLevel > 0" title="返回顶层">顶层</el-button> 
          </el-button-group>
          <el-button @click="clearSelection">清空</el-button>
          <el-button type="primary" @click="confirmSelection">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ArrowDown, Folder } from '@element-plus/icons-vue'

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: [Object, Array],
    default: () => null
  },
  multiple: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: 0 // 0表示无限制，其他值表示最多可选数量
  },
  placeholder: {
    type: String,
    default: '请选择人员'
  },
  users: {
    type: Array,
    default: () => []
  },
  departments: {
    type: Array,
    default: () => []
  },
  loadUsers: {
    type: Function,
    default: null
  },
  loadDepartments: {
    type: Function,
    default: null
  },
  pageSize: {
    type: Number,
    default: 10
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change'])

// 响应式数据
const dialogVisible = ref(false)
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const total = ref(0)
const showPagination = ref(true)
const currentLevel = ref(0) // 当前层级
const breadcrumb = ref([]) // 面包屑导航

// 用户数据
const allUsers = ref([])
const filteredUsers = ref([])
const allDepartments = ref([]) // 所有部门数据

// 已选中的用户
const selectedUsers = ref([])

// 格式化选中项显示文本
const formatSelectedText = computed(() => {
  if (selectedUsers.value.length === 0) return ''
  if (selectedUsers.value.length === 1) {
    return selectedUsers.value[0].name
  }
  return `${selectedUsers.value[0].name} 等${selectedUsers.value.length}人`
})

// 计算是否全选
const isAllSelected = computed(() => {
  if (allUsers.value.length === 0) return false
  
  // 检查所有用户是否都被选中
  return allUsers.value.every(user => isSelected(user))
})

// 监听搜索关键词变化
watch(searchKeyword, (val) => {
  filterUsers()
})

// 监听选中值变化
watch(() => props.modelValue, (val) => {
  if (val) {
    // 确保始终是数组格式
    if (Array.isArray(val)) {
      selectedUsers.value = [...val]
    } else if (val) {
      // 如果是单个对象，转换为数组
      selectedUsers.value = [val]
    } else {
      selectedUsers.value = []
    }
  } else {
    selectedUsers.value = []
  }
}, { immediate: true, deep: true })

// 判断是否选中
const isSelected = (user) => {
  return selectedUsers.value.some(item => item.id === user.id)
}

// 判断复选框是否禁用
const isCheckboxDisabled = (user) => {
  // 如果已达到选择上限且当前用户未被选中，则禁用
  return props.limit > 0 && 
         selectedUsers.value.length >= props.limit && 
         !isSelected(user)
}

// 处理全选变更
const handleSelectAllChange = (val) => {
  if (val) {
    // 全选所有用户
    allUsers.value.forEach(user => {
      if (!isSelected(user)) {
        selectedUsers.value.push(user)
      }
    })
  } else {
    // 取消全选 - 清空所有已选用户
    selectedUsers.value = []
  }
}

// 处理复选框变化
const handleCheckboxChange = (val, user) => {
  if (val) {
    // 添加选中项
    if (!selectedUsers.value.some(item => item.id === user.id)) {
      // 检查是否超过限制
      if (props.limit === 0 || selectedUsers.value.length < props.limit) {
        selectedUsers.value.push(user)
      }
    }
  } else {
    // 移除选中项
    const index = selectedUsers.value.findIndex(item => item.id === user.id)
    if (index !== -1) {
      selectedUsers.value.splice(index, 1)
    }
  }
}

// 处理用户选择
const handleUserSelect = (user) => {
  // 直接切换选中状态
  const index = selectedUsers.value.findIndex(item => item.id === user.id)
  if (index !== -1) {
    // 已选中，移除
    selectedUsers.value.splice(index, 1)
  } else {
    // 未选中，添加（检查限制）
    if (props.limit === 0 || selectedUsers.value.length < props.limit) {
      selectedUsers.value.push(user)
    }
  }
}

// 进入子部门
const goToSubDepartment = (dept) => {
  // 更新面包屑
  breadcrumb.value.push({
    id: dept.id,
    name: dept.name
  })
  
  // 更新当前层级
  currentLevel.value++
  
  // 加载该部门下的用户
  loadUsersByDepartment(dept.id)
}

// 返回上一级
const goToParentLevel = () => {
  if (currentLevel.value <= 0) return
  
  // 更新面包屑
  breadcrumb.value.pop()
  
  // 更新层级
  currentLevel.value--
  
  // 根据当前层级更新数据
  if (currentLevel.value === 0) {
    // 回到顶层，显示部门列表
    filteredUsers.value = []
  } else {
    // 重新加载上一级部门的用户
    const parentId = breadcrumb.value[breadcrumb.value.length - 1].id
    loadUsersByDepartment(parentId)
  }
}

// 返回顶层
const goToTopLevel = () => {
  currentLevel.value = 0
  breadcrumb.value = []
  filteredUsers.value = []
}

// 导航到指定层级
const navigateToLevel = (index) => {
  // 如果点击的是当前层级，不处理
  if (index === breadcrumb.value.length) return
  
  // 截断面包屑到指定层级
  breadcrumb.value = breadcrumb.value.slice(0, index)
  
  // 更新层级
  currentLevel.value = index
  
  // 更新数据
  if (index === 0) {
    // 回到顶层，显示部门列表
    filteredUsers.value = []
  } else {
    // 加载指定层级部门的用户
    const deptId = breadcrumb.value[index - 1].id
    loadUsersByDepartment(deptId)
  }
}

// 根据部门ID加载用户
const loadUsersByDepartment = async (deptId) => {
  loading.value = true
  try {
    // 这里可以根据实际需求进行调整
    // 简单过滤出属于该部门的用户
    let deptUsers = allUsers.value.filter(user => user.deptId === deptId)
    
    // 如果有搜索关键词，进一步过滤
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase()
      deptUsers = deptUsers.filter(user => 
        user.name.toLowerCase().includes(keyword) || 
        user.department.toLowerCase().includes(keyword)
      )
    }
    
    // 更新总数
    total.value = deptUsers.length
    
    // 分页处理
    if (showPagination.value) {
      const start = (currentPage.value - 1) * props.pageSize
      const end = start + props.pageSize
      filteredUsers.value = deptUsers.slice(start, end)
    } else {
      filteredUsers.value = deptUsers
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 打开弹窗
const openDialog = () => {
  dialogVisible.value = true
  // 重置到顶层
  goToTopLevel()
}

// 处理对话框关闭
const handleDialogClose = (done) => {
  done()
}

// 确认选择
const confirmSelection = () => {
  // 根据limit值决定返回的数据格式
  if (props.limit === 1) {
    // 单选模式，返回第一个选中的用户或null
    const selected = selectedUsers.value.length > 0 ? selectedUsers.value[0] : null
    emit('update:modelValue', selected)
    emit('change', selected)
  } else {
    // 多选模式，返回选中的用户数组
    emit('update:modelValue', [...selectedUsers.value])
    emit('change', [...selectedUsers.value])
  }
  dialogVisible.value = false
}

// 清空选择
const clearSelection = () => {
  selectedUsers.value = []
}

// 移除已选用户
const removeSelected = (user, index) => {
  selectedUsers.value.splice(index, 1)
}

// 一键清空所有已选用户
const clearAllSelected = () => {
  selectedUsers.value = []
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  // 重新加载当前部门的用户
  if (breadcrumb.value.length > 0) {
    const deptId = breadcrumb.value[breadcrumb.value.length - 1].id
    loadUsersByDepartment(deptId)
  }
}

// 过滤用户
const filterUsers = () => {
  // 只在非顶层时进行过滤
  if (currentLevel.value > 0 && breadcrumb.value.length > 0) {
    const deptId = breadcrumb.value[breadcrumb.value.length - 1].id
    loadUsersByDepartment(deptId)
  }
}

// 加载用户数据
const loadUserData = async () => {
  loading.value = true
  try {
    if (props.loadUsers) {
      allUsers.value = await props.loadUsers()
    } else if (props.users && props.users.length > 0) {
      allUsers.value = [...props.users]
    } else {
      // 模拟数据
      allUsers.value = [
        {
          id: 1,
          name: '张三',
          department: '管理部门',
          deptId: 1,
          avatar: ''
        },
        {
          id: 2,
          name: '李四',
          department: '管理部门',
          deptId: 1,
          avatar: ''
        },
        {
          id: 3,
          name: '王五',
          department: '技术部门',
          deptId: 2,
          avatar: ''
        },
        {
          id: 4,
          name: '赵六',
          department: '技术部门',
          deptId: 2,
          avatar: ''
        },
        {
          id: 5,
          name: '钱七',
          department: '销售部门',
          deptId: 3,
          avatar: ''
        },
        {
          id: 6,
          name: '孙八',
          department: '销售部门',
          deptId: 3,
          avatar: ''
        },
        {
          id: 7,
          name: '周九',
          department: '技术部门',
          deptId: 2,
          avatar: ''
        },
        {
          id: 8,
          name: '吴十',
          department: '销售部门',
          deptId: 3,
          avatar: ''
        }
      ]
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载部门数据
const loadDepartmentData = async () => {
  loading.value = true
  try {
    if (props.loadDepartments) {
      allDepartments.value = await props.loadDepartments()
    } else if (props.departments && props.departments.length > 0) {
      allDepartments.value = [...props.departments]
    } else {
      // 模拟数据
      allDepartments.value = [
        {
          id: 1,
          name: '管理部门',
          userCount: 2
        },
        {
          id: 2,
          name: '技术部门',
          userCount: 3
        },
        {
          id: 3,
          name: '销售部门',
          userCount: 3
        }
      ]
    }
  } catch (error) {
    console.error('加载部门数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserData()
  loadDepartmentData()
})
</script>

<style scoped lang="scss">
.user-select {
  width: 100%;
}

.select-reference {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  min-height: 32px;

  &:hover {
    border-color: #c0c4cc;
  }

  .select-content {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .placeholder {
    color: #c0c4cc;
  }

  .selected-text {
    color: #606266;
  }

  .arrow-icon {
    color: #c0c4cc;
    transition: transform 0.3s;
  }
}

.user-select-dialog {
  border-radius: 8px;
  overflow: hidden;
  
  .user-select-content {
    .breadcrumb {
      padding: 10px 0;
      border-bottom: 1px solid #eee;
      margin-bottom: 10px;
    }

    .search-box {
      padding: 12px 0;
      margin-bottom: 10px;
    }

    .selected-list {
      margin-bottom: 15px;
      
      .selected-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .clear-all-btn {
          font-size: 12px;
        }
      }
      
      .selected-items {
        .selected-item-tag {
          margin-right: 8px;
          margin-bottom: 8px;
        }
      }
    }

    .department-list, .user-list {
      max-height: 300px;
      overflow-y: auto;
      
      .department-item, .user-item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        border-bottom: 1px solid #f5f5f5;
        cursor: pointer;
        
        &:last-child {
          border-bottom: none;
        }
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        .item-content {
          display: flex;
          align-items: center;
          flex: 1;
          
          .dept-icon {
            color: #409eff;
            margin-right: 10px;
            font-size: 18px;
          }          
          
           .dept-info {
            display: flex;
            align-items: baseline;
            
            .dept-name {
              font-size: 14px;
              color: #333;
            }
            
            .dept-count {
              margin-left: 5px;
              font-size: 12px;
              color: #999;
            }
          }
        }
        
        .item-action {
          display: flex;
          align-items: center;
          
          .sub-dept-btn {
            margin-right: 10px;
          }
        }
      }
    }

    .user-list {
      .user-item {
        .user-avatar {
          margin-right: 12px;
        }
        
        .user-action {
          margin-left: auto;
        }
      }
      
      .select-all {
        padding: 8px 16px;
        border-bottom: 1px solid #f5f5f5;
        background-color: #f9f9f9;
      }
    }

    .no-data {
      text-align: center;
      padding: 20px;
      color: #999;
    }
    
    .limit-tip {
      margin-top: 10px;
      padding: 8px;
      background-color: #f5f7fa;
      border-radius: 4px;
      font-size: 12px;
      color: #999;
      text-align: center;
    }

    .pagination-box {
      padding: 10px 0;
      display: flex;
      justify-content: center;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style>